package cn.lcc.utils.handler.ecoder;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.CorruptedFrameException;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;
import java.util.List;

/**
 * @author 21341
 */
@Slf4j
public class WatchDecoder extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
        try {
            // 确保缓冲区中至少有固定长度的头部数据
            int size = in.readableBytes();
            if (size < 60) {//[3G*8800000015*000D*
                return;
            }
            // 标记当前缓冲区位置
            in.markReaderIndex();
            //起始位
            byte[] startingPosition = new byte[1];
            in.readBytes(startingPosition);
            //"["
            String start = new String(startingPosition);
            if (!"[".equals(start)) {
                throw new CorruptedFrameException("无效的起始位: " + start);
            }
            // 读取固定头部
            byte[] headerBytes = new byte[36];
            //"3G"
            in.readBytes(headerBytes);
            String header = new String(headerBytes);

            in.readBytes(1);
            //[3G*8800000015*000D*LK,50,100,100]
            // 读取设备ID
            String deviceId = in.readCharSequence(15, Charset.defaultCharset()).toString();
            in.readBytes(1);
            // 读取长度
            int length = Integer.parseInt(in.readCharSequence(4, Charset.defaultCharset()).toString(), 16);
            in.readBytes(1);
            // 确保缓冲区中有整个消息
            if (in.readableBytes() < (length + 1)) {
                // 重置到标记位置，以便下一次解码尝试重新读取头部
                in.resetReaderIndex();
                return;
            }
            // 读取有效负载
            String payload = in.readCharSequence(length, Charset.defaultCharset()).toString();
            //结束位
            byte[] endBit = new byte[1];
            //"]"
            in.readBytes(endBit);
            String end = new String(endBit);
            if (!"]".equals(end)) {
                throw new CorruptedFrameException("无效的起始位: " + end);
            }
            // 使用提取的信息创建自定义消息对象
            String message = header + "*" + deviceId + "*" + String.format("%04X", length) + "*" + payload;
            // 将消息添加到输出列表
            out.add(message.getBytes());
        }catch (Exception e) {
            log.error(e.getLocalizedMessage());
        }finally {
//            in.release();
        }
    }
}
